package pl.vanta.utils.xml.xbeans;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import com.thoughtworks.xstream.XStream;

/**
 * @author Krzysztof Wolny (k.wolny@wasko.pl)
 */

class XBeanConverterImplXStream implements XBeanConverter
{
	@Override
	public Object toBean(String xml)
	{
		try
		{
			ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());

			XStream stream = new XStream();

			Object o = stream.fromXML(bais);

			return o;
		}
		catch (Exception ex)
		{
			ex.printStackTrace();

			return null;
		}
	}

	@Override
	public String toXml(Object object)
	{
		try
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			XStream stream = new XStream();

			stream.toXML(object, baos);

			return baos.toString();

		}
		catch (Exception ex)
		{
			ex.printStackTrace();

			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T toBean(String xml, Class<T> clazz)
	{
		Object o = toBean(xml);

		if (clazz.isInstance(o))
		{
			return (T) o;
		}
		else
		{
			return null;
		}
	}
}
